package com.compus.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.compus.entity.po.User;
import com.compus.entity.vo.Result;
import com.compus.entity.vo.UserLoginDto;
import com.compus.service.UserService;
import com.compus.utils.Md5Utils;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<UserLoginDto> login(@RequestBody User user) {
        User one = userService.lambdaQuery()
                .eq(User::getPhone, user.getPhone())
                .eq(User::getPassword, Md5Utils.encryption(user.getPassword()))
                .one();
        if (one == null) {
           return Result.fail("用户名或密码错误");
        }
        StpUtil.login(one.getId());
        StpUtil.getSession().set("name", one.getName());
        UserLoginDto loginDto = new UserLoginDto();
        loginDto.setName(one.getName());
        loginDto.setToken(StpUtil.getTokenValue());
        return Result.success(loginDto);
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        User one = userService.lambdaQuery()
                .eq(User::getPhone, user.getPhone())
                .one();
        if (one != null) {
            return Result.fail("手机号已被注册");
        }
        user.setPassword(Md5Utils.encryption(user.getPassword()));
        userService.save(user);
        return Result.success();
    }

}
